package compound.repository

import compound.repository.entries.Compound
import util.ConvertHelper

/**
 * provides us with transformations
 */
class TransformController {

  /**
   * does the actual converting of data
   */
  ConvertService convertService
  DataExportService dataExportService = new DataExportService();

  def index = {

    String from = "-1"
    String to = "-1"
    String idValue = ""

    if (params.from != null) {
      from = params.from
    }

    if (params.to != null) {
      to = params.to
    }

    if (params.idValue != null) {
      idValue = params.idValue
    }


    return [fromFields: ConvertHelper.getInstance().getFromConversions(), toFields: ConvertHelper.getInstance().getToConversions(), idValue: idValue, from: from, to: to]
  }

  /**
   * exspects 3 params and convert them to the given result
   * using the converter service
   */
  def transform = {

    String from = params.from
    String to = params.to
    String idValue = params.idValue

    log.info "$from -> $to for $idValue"

    def valid = validate(idValue, flash, from, to)
    if (valid != null) {
      flash.message = valid
      redirect(action: "index")
    }



    log.debug("before decode: ${idValue}")
    println "id: ${idValue}"
    idValue = URLDecoder.decode(idValue, "UTF-8")
    log.debug("after decode: ${idValue}")


    if (params?.format && params.format != "html") //Export
    {

      println "======== In Upload =============";
      //call the service to conver the data
      Collection<Map<Compound, ?>> transform = convertService.convert(from, to, idValue)

      dataExportService.exportTransform(transform, response, params)

    } else {

      def result =  doTransform(params, convertService, from, to, idValue)
      render (template:'transform', model: [transform:result.result, idValue: idValue, from: from, to: to, max: params.max, offset: params.offset, total: result.total])

    }

  }

  private def doTransform(Map params, ConvertService convertService, String from, String to, String idValue) {
    if (params.offset == null || params.offset.toString().equals("0")) {
      params.put("offset", 0);
    } else {
      params.put("offset", Long.parseLong("0" + params.offset.toString()));
    }

    if (params.max == null || params.max.toString().equals("0")) {
      params.put("max", 10);
    } else {
      params.put("max", Long.parseLong("0" + params.max.toString()));
    }

    //call the service to to get Count of the data
    Long total = 0;
    if (params.total == null || params.total.toString().equals("0")) {
      total = convertService.getCount(from, to, idValue)
    } else {
      total = Long.parseLong(params.total.toString())
    }

    //call the service to conver the data
    Collection<Map<Compound, ?>> result = convertService.convert(from, to, idValue, params)

    return [result:result,total:total]
  }

  private def validate(String idValue, Map flash, String from, String to) {
    if (idValue == null || idValue.trim().length() == 0) {
      return "Error! Id parameter is mandatory, Please Enter id."
    } else {
      if (from == null || from.toString().equalsIgnoreCase("NULL")) {
        return "Error! From parameter is mandatory."
      } else {
        if (to == null || to.toString().equalsIgnoreCase("NULL")) {
          return "Error! To parameter is mandatory."
        }
      }
    }
    return null;
  }

  def transform_remote = {

    String from = params.from
    String to = params.to
    String idValue = params.idValue

    log.info "$from -> $to for $idValue"


    def valid = validate(idValue, flash, from, to)

    if (valid != null) {
      render "<div class='errors'>${valid}</div>"
    }
    else {
      def result = doTransform(params, convertService, from, to, idValue)
      render (template:'transform', model: [transform:result.result, idValue: idValue, from: from, to: to, max: params.max, offset: params.offset, total: result.total])
    }
  }
  /**
   * returns the provide formats
   */
  static List getFormats() {
    return ['xml', 'json', 'csv', 'excel', 'ods', 'pdf', 'rtf']
  }

  def show_help_remote ={
    render """<div class="message">"Please enter an ID from the 'From' list, which you like to convert and select the from and to database identifiers</div>"""    
  }

}
